package tk.kikt

import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler

import java.net.InetAddress

class HelloServerHandler : SimpleChannelInboundHandler<String>() {

    @Throws(Exception::class)
    override fun channelRead0(ctx: ChannelHandlerContext, msg: String) {
        val name = ctx.name()

        // 收到消息直接打印输出
        println(ctx.channel().remoteAddress().toString() + " Say : " + msg)

        // 返回客户端消息 - 我已经接收到了你的消息
        ctx.writeAndFlush("your name =$name, Received your message :$msg\n")

        val mapping = MappingHandler.getMapping()
        mapping.forEach { _, channel ->
            channel.getChannel().writeAndFlush("rec message $msg")
        }
    }

    /*
     *
     * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)
     *
     * channelActive 和 channelInActive 在后面的内容中讲述，这里先不做详细的描述
     * */
    @Throws(Exception::class)
    override fun channelActive(ctx: ChannelHandlerContext) {

        println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !")

        ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().hostName + " service!\n")

        super.channelActive(ctx)
    }
}
